<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="摄像头名称：">
							<el-input v-model="transferVal1" placeholder="摄像头名称" />
						</el-form-item>
						<el-form-item label="设备名称：">
							<el-input v-model="transferVal2" placeholder="设备名称" />
						</el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('algorithmModelRelationshipBind1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_DeviceCode" label="设备编码" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="设备名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="v_DeviceName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="scope">
													<span> {{ scope.row.v_DeviceName }} </span>
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="摄像头名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="v_CameraName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="scope">
													<span> {{ scope.row.v_CameraName }} </span>
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_RemoteCameraId" label="远程摄像头唯一标识" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="v_LocationFullName" label="区域全称" align="center" />

										<el-table-column min-width="100" label="操作" align="center" fixed="right">
											<el-table-column min-width="100" align="center" fixed="right">
												<template #header>
													<el-button text @click="searchClick" icon="ele-Search" type="primary"> 查询 </el-button>
													<el-button text @click="resetClick" icon="ele-Refresh"> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button @click="queryClick(scope.row)" class="icon-e" icon="ele-View" size="small" text type="primary">详情</el-button>
														<el-button v-if="$hasPer('algorithmModelRelationshipBind2:delete')" @click="deleteHandle(scope.row.n_Id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog v-model="showDialogVisible" title="新增" width="50%" @close="cancelUseClick">
			<el-form label-width="110px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="name" label="摄像头">
							<el-select v-model="selectVal1" placeholder="摄像头" style="width: 100%">
								<el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备列表">
							<el-tree-select style="width: 100%" v-model="selectVal2" :data="deviceTree" :render-after-expand="false" @node-click="handleNodeClick" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 详情 -->
		<!-- 详情 -->
		<el-dialog v-model="dialogVisible" title="详情" width="50%" @close="dialogVisible = false">
			<el-divider content-position="left"> 基本信息 </el-divider>
			<el-descriptions class="margin-top" :column="2" border>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">设备编码</div>
					</template>
					{{ descriptionsData.v_DeviceCode }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">设备名称</div>
					</template>
					{{ descriptionsData.v_DeviceName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">设备Id</div>
					</template>
					{{ descriptionsData.n_CameraId }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">摄像头名称</div>
					</template>
					{{ descriptionsData.v_CameraName }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label>
						<div class="cell-item">远程摄像头唯一标识</div>
					</template>
					{{ descriptionsData.v_RemoteCameraId }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label>
						<div class="cell-item">远程摄像头唯一标识码</div>
					</template>
					{{ descriptionsData.v_RemoteCameraCode }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">区域名称</div>
					</template>
					{{ descriptionsData.v_LocationName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">区域全称</div>
					</template>
					{{ descriptionsData.v_LocationFullName }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label>
						<div class="cell-item">区域Id</div>
					</template>
					{{ descriptionsData.n_LocationId }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">区域父路径集</div>
					</template>
					{{ descriptionsData.v_LocationParentIds }}
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import {
	getCameraDeviceBindDetailApi,
	getCameraDeviceBindApi,
	deleteCameraDeviceBindApi,
	addCameraDeviceBindApi,
	getCameraDeviceBindTreeApi,
	getCameraDeviceBindCameraListApi,
} from '/@/api/its/algorithm-model-device-bind';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';

/***** 查询 *****/
let searchObj: any = reactive({});
const transferVal1 = ref();
const transferVal2 = ref();
const searchClick = () => {
	// searchObj.v_CameraName = transferVal1.value
	// searchObj.v_DeviceName = transferVal1.value

	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

/*** resetClick 重置按钮 */
const resetClick = () => {
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};

/***** 新增 *****/
const showDialogVisible = ref(false);
const ruleForm = reactive({
	n_CameraId: 0, //摄像头Id
	n_DeviceId: 0, //设备
	v_DeviceCode: '', //设备编码
	v_DeviceName: '', //设备名称
	n_LocationId: 0, //区域Id
	v_LocationName: '', //区域名称
	v_LocationFullName: '', //区域全称
	v_LocationParentIds: '', //区域父路径集
});

const addNodeClick = async () => {
	const res1 = await getCameraDeviceBindCameraListApi();
	options1.value = res1.data;
	showDialogVisible.value = true;
	const res = await getCameraDeviceBindTreeApi();
	deviceTree.value = transformData(res.data);
};

/*** 删除 */
const deleteHandle = async (val: String | Number) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: val };
			try {
				let res: any = await deleteCameraDeviceBindApi(param);
				if (res.success) {
					getData();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

/***** 新增表单校验和事件 *****/
const ruleFormRef = ref();
const rules = reactive({
	selectVal1: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	selectVal2: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});
const cancelUseClick = () => {
	showDialogVisible.value = false;

	ruleForm.n_CameraId = 0;
	ruleForm.n_DeviceId = 0;
	ruleForm.v_DeviceCode = '';
	ruleForm.v_DeviceName = '';
	ruleForm.n_LocationId = 0;
	ruleForm.v_LocationName = '';
	ruleForm.v_LocationFullName = '';
	ruleForm.v_LocationParentIds = '';

	selectVal.value = '';
	selectVal2.value = '';
	selectVal1.value = '';

	options1.value = [];
	deviceTree.value = [];
};
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (!selectVal.value.b_IsDevice) return ElMessage.warning('当前节点不可用');
			ruleForm.n_CameraId = selectVal1.value;
			ruleForm.n_DeviceId = selectVal.value.n_DeviceId;
			ruleForm.v_DeviceCode = selectVal.value.v_DeviceCode;
			ruleForm.v_DeviceName = selectVal.value.v_DeviceName;
			ruleForm.n_LocationId = selectVal.value.n_AreaId;
			ruleForm.v_LocationName = selectVal.value.v_AreaName;
			ruleForm.v_LocationFullName = selectVal.value.v_AreaFullName;
			ruleForm.v_LocationParentIds = selectVal.value.v_AreaParentIds;
			addCameraDeviceBindApi(ruleForm).then(() => {
				cancelUseClick();
				getData();
			});
		} else {
			console.log('error submit!', fields);
		}
	});
};
// 详情
const dialogVisible = ref(false);
const descriptionsData = ref();
const queryClick = async (row: any) => {
	descriptionsData.value = null;
	const res = await getCameraDeviceBindDetailApi({ id: row.n_Id });
	descriptionsData.value = res.data;
	dialogVisible.value = true;
};

//设备树
const selectVal1 = ref();
const selectVal2 = ref();
const selectVal = ref();
const handleNodeClick = (data: any) => {
	selectVal.value = data.item;
};

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getCameraDeviceBindApi, {}, searchObj);
const deviceTree: any = ref([]);
function transformData(data) {
	return data.map((item) => ({
		item: item,
		label: item.v_Name,
		value: item.n_Id,
		children: (item.children || [])
			.map((child) => {
				let deviceInfo = {};

				if (child.b_IsDevice && child.n_DeviceId) {
					deviceInfo = {
						deviceId: child.n_DeviceId,
						deviceCode: child.v_DeviceCode,
						deviceName: child.v_DeviceName,
					};
				}

				return {
					...transformData([child])[0],
					...(deviceInfo.deviceId ? { deviceInfo } : {}),
					children: !child.b_IsDevice ? transformData(child.children || []) : [],
				};
			})
			.filter((node) => node.value || node.deviceInfo),
	}));
}

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'v_DeviceName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'v_DeviceName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '设备名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'v_CameraName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'v_CameraName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '摄像头名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};

const options1 = ref([]);
onMounted(async () => {
	initInfoFun();
});
</script>

<style lang="scss">
@import '../../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
